<script>
    import Userinfo from './userinfo.svelte'
    import {createEventDispatcher, onDestroy, onMount} from "svelte";
    import {setlogin, thisuser, wsrecon} from "../src/main";
    import {now} from "svelte/internal";
    import messages, {fileList, isLogin, users} from "../store.js";
    import {push} from "svelte-spa-router";

    // let users = [
    //     {id:1,name:'Lwz',desc:'1576886'},
    //     {id:2,name:'LB',desc:'12525'},
    //     {id:2,name:'HX',desc: 'abcd'},
    //     {id:2,name:'ZF',desc: 'opq'},
    //     {id:2,name:'GY',desc: 'read'},
    //     {id:2,name:'LB',desc: 'cat'},
    //     {id:2,name:'CBA',desc: 'say hello'},
    // ];

    var msg;
    var msgs=[];

    onMount(
        async ()=>{
            fetch("/api/users",{
                method:"Get",
            }).then((res)=>{
                // console.log(res)
                return res.json()
            }).then((res)=>{
                users.update((cur)=>{
                    return res.users
                })
            })
            // console.log(ws)
            // console.log(ws.readyState)
            // if(ws==null||ws===undefined||ws.readyState===2||ws.readyState===3){
            //     wsrecon()
            // }
            // console.log(ws.readyState)
        }
    )
    const ws = new WebSocket("ws://"+location.host+"/ws");

    function sentMsg() {
        //下面这句可以多次发送，当作是聊天。
        ws.send(JSON.stringify(
            {
                /*
                * 0 登录  1 聊天 2 退出
                * */
                "type":1,
                "account":thisuser,
                "from":thisuser,
                // "msg":thisuser+"=> "+msg
                "msg":msg
            }
        ))
        // messages.update(cur=>{
        //     let m={
        //         "msg":msg,
        //         "from":thisuser,
        //         "to":"",
        //         "at":""
        //     }
        //     return [...cur,m]
        // })
        // console.log($messages)
        msg=""
    }
    ws.onopen = function (ev) {
        ws.send(JSON.stringify(
            {
                "type":0,
                "from":thisuser,
                "msg":thisuser+" 登陆了"
            }
        ))
    };
    ws.onmessage = function (ev) {
        // console.log(ev)
        if (ev.data){
            let newmsg=JSON.parse(ev.data)
            messages.update(cur=>{
                return [...cur,newmsg]
            })
            if(newmsg.type===3){
                fetch("/api/users",{
                    method:"Get",
                }).then((res)=>{
                    // console.log(res)
                    return res.json()
                }).then((res)=>{
                    users.update((cur)=>{
                        return res.users
                    })
                    // console.log(users)
                })
            }else if(newmsg.type===4){
                fetch("/api/getfile",{
                    method:"Get",
                }).then((res)=>{
                    // console.log(res)
                    return res.json()
                }).then((res)=>{
                    fileList.update((cur)=>{
                        return res.files
                    })
                    // console.log(users)
                })
            }
        }
        // console.log($messages)
    };
    ws.onclose=function(ev){
        ws.send(JSON.stringify({
            "type":2,
            "from":thisuser,
            "msg":thisuser+" 退出"
        }))
    }

    onDestroy(async ()=>{
        // ws.send(JSON.stringify({
        //     "type":2,
        //     "from":thisuser,
        //     "msg":thisuser+" 退出"
        // }))
        // await ws.close()
    })

    function logout() {
        fetch("/api/logout").then((res)=>{
            return res.json()
        }).then((r)=>{
            if(r.status===0){
                setlogin(false)
                isLogin.update(prev=>{
                    return false
                })
            }
        })
        push("/")
    }

    function handleMessage(user) {
        console.log(user)
        var msg = "确定删除？";

        if (confirm(msg) === true) {
            if (user === thisuser) {
                alert("删除自己请前往注销")
                return
            }
            fetch("/api/deluser", {
                method: "Post",
                body: JSON.stringify({
                    user: user
                })
            }).then((r) => {
                return r.json()
            }).then((r) => {
                console.log(r)
                if (r.status === 0) {
                    ws.send(JSON.stringify({
                        "type":3,
                        "from":thisuser,
                        "msg":"用户列表更新"
                    }))
                } else {
                    alert("删除失败")
                }
            })
        } else {

        }
    }
</script>

<style>
    .userlist{
        width: 25%;
        height: 580px;
        /*align-content: center;*/
        border: 1px solid #aaa;
        border-radius: 2px;
        box-shadow: 2px 2px 8px rgba(0,0,0,0.1);
        padding: 1em;
        margin: 1em 1em;
    }
    .title {
        margin: 0 0 1em 0;
        padding: 1em 0;
        border-bottom: 1px solid #ff3e00
    }
    .btn{
        width: 40%;
        margin: 10px;
        border-radius: 12px;
        height: 35px;
    }
</style>

<div class="userlist">
    <span style="float: top">
        <p class="title" >用户列表</p>
    </span>
    <div style="overflow-y: scroll;height: 340px;margin-bottom: 10px">
        {#each $users as {nick,account}}
        <Userinfo user="{account}" on:message={()=>handleMessage(account)} >
            <span slot="name">
                {nick}
            </span>
            <span slot="info">
                {account}
            </span>
        </Userinfo>
        {:else }
            Loading
        {/each}
        <slot></slot>
    </div>
    <span style="float: bottom">
        <textarea bind:value={msg} rows="3" cols="30" style="font-size: 24px; width: 85%;margin:10px 0 10px 0"></textarea><br>
        <span>
        <button class="btn" on:click={logout}>退出</button>
        <button class="btn" on:click={sentMsg} style="background-color: rgba(8,159,238,1);">发送</button>
        </span>
<!--        <input type="button" value="发送" onclick="send()">-->
    </span>
</div>